import { ElLoading as Loading } from 'element-plus';
import axios from 'axios';

let requestCount = 0;
let loading;
function showLoading(text = '加载中...') {
  if (requestCount === 0) {
    loading = Loading.service({
      lock: true,
      text,
      target: 'body',
      background: 'rgba(0, 0, 0, 0.7)',
    })
  }
  requestCount++;
}
function hideLoading() {
  if (requestCount > 0) {
    requestCount--;
  }
  !requestCount && loading.close();
}
export default function (url, options = {}) {
  return (params, wait) => new Promise(resolve => {
    if (typeof params === 'boolean') {
      wait = params;
      params = {};
    } else if (!params) {
      params = {};
    }
    if (wait === undefined) {
      wait = true;
    }
    // params.userId = _.get(store.state, 'personal.userId', params.userId);
    params = options.preFormat ? options.preFormat(params) : params;
    const method = options.get ? axios.get : axios.post;
    console.log('[' + url + '] ' + (options.get ? 'get ' : '') + 'send:', JSON.parse(JSON.stringify(params || {})));
    wait && showLoading();
    method(url, options.get ? { params } : params).then(res => {
      const data = options.postFormat ? options.postFormat(res.data) : res.data;
      console.log(`${url}[recv]${options.get ? '[get]' : ''}:`, JSON.parse(JSON.stringify(data)));
      wait && hideLoading();
      resolve(data);
    }).catch(error => {
      console.log(`${url}[error]${options.get ? '[get]' : ''}:`, error);
      wait && hideLoading();
      resolve({ message: error.message });
    });
  });
};
